import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { orderApi } from '../services/api';

export function useOrders() {
  // 订单数据
  const orders = ref([]);
  const loading = ref(false);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const searchKeyword = ref('');
  const status = ref('');

  // 加载订单列表
  const loadOrders = async () => {
    loading.value = true;
    try {
      const queryParams = {
        page: currentPage.value,
        limit: pageSize.value
      };
      
      // 状态筛选（前端pending/printed转换为后端0/1）
      if (status.value) {
        queryParams.print_status = status.value === 'pending' ? 0 : 1;
      }
      
      // 搜索关键词
      if (searchKeyword.value) {
        queryParams.keyword = searchKeyword.value;
      }
      
      const response = await orderApi.getOrders(queryParams);
      
      if (response && Array.isArray(response.orders)) {
        // 处理订单数据，确保数据格式正确
        orders.value = response.orders.map(order => {
          // 转换items字段为数组
          if (typeof order.items === 'string') {
            try {
              order.items = JSON.parse(order.items);
            } catch (e) {
              order.items = [];
            }
          }
          // 添加前端状态字段
          if (order.print_status !== undefined) {
            order.status = order.print_status === 1 ? 'printed' : 'pending';
          }
          return order;
        });
        total.value = response.total || 0;
      } else {
        orders.value = [];
        total.value = 0;
        ElMessage.warning('订单数据格式异常');
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
      ElMessage.error('获取订单列表失败');
      orders.value = [];
      total.value = 0;
    } finally {
      loading.value = false;
    }
  };

  // 处理搜索
  const handleSearch = () => {
    currentPage.value = 1;
    loadOrders();
  };

  // 处理页码变化
  const handlePageChange = (val) => {
    currentPage.value = val;
    loadOrders();
  };

  // 处理每页条数变化
  const handlePageSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    loadOrders();
  };

  // 打印订单
  const handlePrintOrder = async (orderId, printerInfo = {}) => {
    try {
      const response = await orderApi.printOrder(orderId, printerInfo);
      if (response && response.success) {
        ElMessage.success('打印成功');
        loadOrders(); // 重新加载订单列表
        return true;
      } else {
        ElMessage.error('打印失败');
        return false;
      }
    } catch (error) {
      console.error('打印订单失败:', error);
      ElMessage.error('打印失败');
      return false;
    }
  };

  // 更新订单
  const handleUpdateOrder = async (orderId, orderData) => {
    try {
      const response = await orderApi.updateOrder(orderId, orderData);
      if (response && response.id) {
        ElMessage.success('订单更新成功');
        loadOrders(); // 重新加载订单列表
        return true;
      } else {
        ElMessage.error('订单更新失败');
        return false;
      }
    } catch (error) {
      console.error('更新订单失败:', error);
      ElMessage.error('订单更新失败');
      return false;
    }
  };

  // 删除订单
  const handleDeleteOrder = async (orderId) => {
    try {
      const response = await orderApi.deleteOrder(orderId);
      if (response && response.success) {
        ElMessage.success('订单删除成功');
        loadOrders(); // 重新加载订单列表
        return true;
      } else {
        ElMessage.error('订单删除失败');
        return false;
      }
    } catch (error) {
      console.error('删除订单失败:', error);
      ElMessage.error('删除失败');
      return false;
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    try {
      if (!dateString) return '-';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (e) {
      return dateString || '-';
    }
  };

  // 格式化订单状态
  const formatOrderStatus = (status) => {
    const statusMap = {
      0: { text: '待打印', type: 'warning' },
      1: { text: '已打印', type: 'success' }
    };
    return statusMap[status] || { text: '未知', type: 'info' };
  };

  return {
    orders,
    loading,
    currentPage,
    pageSize,
    total,
    searchKeyword,
    status,
    loadOrders,
    handleSearch,
    handlePageChange,
    handlePageSizeChange,
    handlePrintOrder,
    handleUpdateOrder,
    handleDeleteOrder,
    formatDate,
    formatOrderStatus
  };
}